package org.yray.sip.rtp.data;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.yray.sip.utils.CMG711;
import org.yray.sip.utils.G711Grabber;
import org.yray.sip.utils.IcspBeanHolder;
import org.yray.sip.wav.WavUtils;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class MediaWav {
    private MediaWav(){}

    private static Map<String,MediaSpeaker> speakerMap=new ConcurrentHashMap<>();
    private static ReentrantLock createMediaSpeakerLock=new ReentrantLock();
    private static String wavPath="D:\\test\\wav";

    public static byte[] getWav(String wavId,String speaker)
    {
        MediaSpeaker mediaSpeaker=speakerMap.computeIfAbsent(speaker,v->new MediaSpeaker());
        byte[] wavs= mediaSpeaker.getWav(wavId);
        if(wavs==null)
        {
            //偿试读下文件
            String wavFileName=wavPath + File.separator+speaker+File.separator+wavId+".wav";
            try {
                byte[] bs=FileUtils.readFileToByteArray(new File(wavFileName));
                if(!WavUtils.isWav8K(bs))
                {
                    log.error("file={},err format",wavFileName);
                    return null;
                }
                wavs = new byte[bs.length - 44];
                System.arraycopy(bs, 44, wavs, 0, wavs.length);
                wavs = G711Grabber.wavBody2G711Body(wavs);
                mediaSpeaker.putWav(wavId,wavs);
            } catch (IOException e) {
                log.error("录音文件不存在,{}",wavFileName);
            }
        }
        return wavs;
    }

    public static void cleanWav(String speaker)
    {
        MediaSpeaker mediaSpeaker=speakerMap.get(speaker);
        if(mediaSpeaker!=null)
        {
            mediaSpeaker.cleanWav();
        }
    }

    public static void putWav(String speaker,String wavKey,byte[] bs)
    {
        MediaSpeaker mediaSpeaker=speakerMap.computeIfAbsent(speaker,v->new MediaSpeaker());
        mediaSpeaker.putWav(wavKey,bs);
    }


    private static MediaSpeaker createMediaSpeaker(String speaker)
    {
        MediaSpeaker m=new MediaSpeaker();
        speakerMap.put(speaker,m);
        return m;
    }

}
